import 'package:app_router_demo/pages/home_page.dart';
import 'package:app_router_demo/pages/login/login_code_page.dart';
import 'package:app_router_demo/pages/login/login_index_page.dart';
import 'package:app_router_demo/pages/login/login_phone_page.dart';
import 'package:app_router_demo/pages/message_page.dart';
import 'package:app_router_demo/pages/profile_page.dart';
import 'package:app_router_demo/pages/tab_page.dart';
import 'package:app_router_demo/providers/auth_provider.dart';
import 'package:auto_route/auto_route.dart';
import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart'; // 导入 Navigator

part 'app_router.gr.dart';

@AutoRouterConfig(replaceInRouteName: 'Page,Route')
class AppRouter extends RootStackRouter {
  final AuthGuard authGuard; // 注入 AuthGuard
  AppRouter({required this.authGuard});

  @override
  List<AutoRoute> get routes => [
    AutoRoute(
      page: LoginIndexRoute.page,
      path: '/login', // 登录首页，作为应用的初始路由
      initial: true,
      // children: [
      //   ,
      // ],
    ),
    AutoRoute(
      page: LoginPhoneRoute.page,
      path: '/phone-login', // 手机登录页，路径为 /login/phone-login
    ),
    AutoRoute(
      page: LoginCodeRoute.page,
      path: '/code-login:phoneNum/:countryCode', // 手机登录页，路径为 /login/phone-login
    ),
    AutoRoute(
      page: TabRoute.page,
      path: '/main', // 应用主页（TabBar），需要登录才能访问
      guards: [authGuard], // 应用 AuthGuard 保护 TabRoute
      children: [
        AutoRoute(page: HomeRoute.page, path: 'home', initial: true), // 默认显示首页
        AutoRoute(page: MessageRoute.page, path: 'message'),
        AutoRoute(page: ProfileRoute.page, path: 'profile'),
      ],
    ),
  ];

  @override
  final List<NavigatorObserver> navigatorObservers = [
    // 在这里添加 FlutterSmartDialog.observer
    FlutterSmartDialog.observer,
    // 如果你还有其他的导航观察者，也在这里添加
    // MyAnalyticsObserver(),
  ];
}

// AuthGuard 再次确认，检查 isLoggedIn 状态
class AuthGuard extends AutoRouteGuard {
  final AuthProvider authProvider; // 直接持有 AuthProvider 实例

  AuthGuard({required this.authProvider});

  @override
  void onNavigation(NavigationResolver resolver, StackRouter router) {
    debugPrint(
      'AuthGuard: 导航到 ${resolver.route.fullPath}, isLoggedIn = ${authProvider.isLoggedIn}',
    );
    if (authProvider.isLoggedIn) {
      resolver.next(true); // 已登录，放行
    } else {
      // 未登录，重定向到登录页
      debugPrint('AuthGuard: 用户未登录，重定向到 LoginRoute');
      router.replace(const LoginIndexRoute()); // 重定向到登录首页
    }
  }
}
